#pragma once
#include <netinet/in.h>
#include <string_view>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
class tcp_server{
public:
    tcp_server(std::string_view ip, uint16_t port){
        m_sock = socket(PF_INET, SOCK_STREAM, 0);
        if (m_sock == -1){
            perror("创建socket失败\n");
            exit(-1);
        }

        memset(&m_sockaddr, 0, sizeof(m_sockaddr));
        m_sockaddr.sin_family = AF_INET;
        m_sockaddr.sin_port = htons(port); 
        if (inet_pton(AF_INET, ip.data(), &m_sockaddr.sin_addr) == -1){
            perror("不是一个有效的IP地址\n");
            exit(-1);
        } 

        if (bind(m_sock, reinterpret_cast<sockaddr*>(&m_sockaddr), sizeof(m_sockaddr)) == -1){
            perror("bind函数执行时发生错误\n");
            exit(-1);
        }

        if (listen(m_sock, 5) == -1){
            perror("listen函数执行时发生失败\n");
            exit(-1);
        }
    }

    tcp_server(uint16_t port){
        m_sock = socket(PF_INET, SOCK_STREAM, 0);
        if (m_sock == -1){
            perror("创建socket失败\n");
            exit(-1);
        }

        memset(&m_sockaddr, 0, sizeof(m_sockaddr));
        m_sockaddr.sin_family = AF_INET;
        m_sockaddr.sin_port = htons(port);
        m_sockaddr.sin_addr.s_addr = INADDR_ANY;


        if (bind(m_sock, reinterpret_cast<sockaddr*>(&m_sockaddr), sizeof(m_sockaddr)) == -1){
            perror("bind函数执行时发生错误\n");
            exit(-1);
        }

        if (listen(m_sock, 5) == -1){
            perror("listen函数执行时发生失败\n");
            exit(-1);
        }
    }

    int accept(){
        sockaddr_in client_sockaddr;
        socklen_t client_socklen = sizeof(client_sockaddr);
        int client_sock = ::accept(m_sock, reinterpret_cast<sockaddr*>(&client_sockaddr), &client_socklen);
        return client_sock;
    }

    int get_sockfd(){
        return m_sock;
    }
private:
    int m_sock;
    sockaddr_in m_sockaddr;
};